package com.health.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.health.common.PageBean;
import com.health.dto.SetmealQueryDTO;
import com.health.exception.ParameterInvalidException;
import com.health.exception.SetmealCodeExistedException;
import com.health.exception.SetmealNameExistedException;
import com.health.mapper.SetmealCheckgroupMapper;
import com.health.mapper.SetmealMapper;
import com.health.pojo.Setmeal;
import com.health.pojo.SetmealCheckgroup;
import com.health.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author zgp
 * @version V1.0
 * @date 2025-01-19 19:35
 */
@Service
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private SetmealCheckgroupMapper setmealCheckgroupMapper;



    @Override
    public PageBean<Setmeal> getPageList(SetmealQueryDTO setmealQueryDTO) {
        PageHelper.startPage(setmealQueryDTO.getCurrentPage(), setmealQueryDTO.getPageSize());
        Page<Setmeal> setmealPage = setmealMapper.selectPageList(setmealQueryDTO);
        return new PageBean<>(setmealPage.getTotal(), setmealPage.getResult());
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void addSetmeal(Setmeal setmeal, List<Integer> checkgroupIds) {
        // 参数校验：编码、名称、价格、包含检查组、图片不能为空
        if(ObjUtil.isEmpty(setmeal.getCode())
                || ObjUtil.isEmpty(setmeal.getName())
                || ObjUtil.isEmpty(setmeal.getPrice())
                || ObjUtil.isEmpty(setmeal.getImg())
                || CollUtil.isEmpty(checkgroupIds)
        ){
            throw new ParameterInvalidException("参数非法");
        }
        // 编码、名称不能重复
        Setmeal existSetmeal = setmealMapper.selectByCode(setmeal.getCode());
        if(ObjUtil.isNotEmpty(existSetmeal)){
            throw new SetmealCodeExistedException("套餐编码已存在");
        }
        existSetmeal = setmealMapper.selectByName(setmeal.getName());
        if(ObjUtil.isNotEmpty(existSetmeal)){
            throw new SetmealNameExistedException("套餐名称已存在");
        }
        // 业务处理
        if(ObjUtil.isEmpty(setmeal.getSex())){
            setmeal.setSex("0");
        }
        if(ObjUtil.isEmpty(setmeal.getAge())){
            setmeal.setAge("0-100");
        }
        // 新增套餐基本信息
        setmealMapper.insert(setmeal);
        // 新增套餐对应检查组信息
        List<SetmealCheckgroup> setmealCheckgroups = new ArrayList<>();
        checkgroupIds.forEach(o -> setmealCheckgroups.add(new SetmealCheckgroup(setmeal.getId(), o)));
        setmealCheckgroupMapper.insertOfBatch(setmealCheckgroups);
    }
}
